import { Component, OnInit } from '@angular/core';
import {Role} from "../../roles/role";
import {Router, ActivatedRoute} from "@angular/router";
import {ResponseUtil} from "../../../../util/response-util";
import {PageSubject} from "../../../../util/page-subject";
import {RolesService} from "../../roles/roles.service";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {AccountsService} from "../accounts.service";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgResult} from "../../../../models/msg-result";
import {FormGroup, FormBuilder, Validators} from "@angular/forms";
import {MsgConstants} from "../../../../constants/constants";

@Component({
  selector: 'app-account-create-role',
  templateUrl: './account-create-role.component.html'
})
export class AccountCreateRoleComponent implements OnInit {

  role :Role;

  roleId :string;

  accountId :string;

  menuId :string;

  roleForm: FormGroup;

  constructor(
    private router : Router,
    private route : ActivatedRoute,
    private responseUtil : ResponseUtil,
    private fb: FormBuilder,
    private pageSubject : PageSubject,
    private rolesService: RolesService,
    private dialogService : OneDialogService,
    private accountsService : AccountsService
  ) {
  this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    //获取数据
    if(!!this.route.snapshot.params["accId"]){
      this.accountId=this.route.snapshot.params["accId"];
    }
     this.menuId = this.route.snapshot.params["mid"];
  }

  /**
   * 面包屑导航
   */
  private pushPage(){
    let path = new Path("权限系统","");
    this.pageSubject.pushPage("账户管理","创建角色",path);
  }



  /**
   * 构造表单
   */
  buildForm(): void {
    this.roleForm = this.fb.group({
      'roleId': [this.role.roleId],
      'roleName': [this.role.roleName, [
        Validators.required,
        Validators.maxLength(30),
        Validators.pattern(/^(?!_)(?!.*?_$)[(a-zA-Z0-9_\-)\u4e00-\u9fa5]+$/)
      ]],
      'description': [this.role.description, [
        Validators.maxLength(50),
      ]]
    });

    this.roleForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }


  /**
   * 值变化监听
   * @param data
   */
  onValueChanged(data?: any) {
    if (!this.roleForm) {
      return;
    }
    const form = this.roleForm;
    for (const field in this.formErrors) {
      this.formErrors[field] = '';
      const control = form.get(field);
      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }

  /**
   * 校验字段
   * @type {{name: string; code: string}}
   */
  formErrors = {
    'roleName': '',
    'description': '',
  };

  /**
   * 校验提示信息
   * @type {{name: {required: string; maxlength: string}; code: {required: string; maxlength: string; pattern: string}}}
   */
  validationMessages = {
    'roleName': {
      'required': '角色名不能为空',
      'maxlength': '长度不能超过30',
      'pattern': '只能由汉字或字母、数字、下划线、中划线组成，不能以下划线开头或结尾'
    },
    'description': {
      'maxlength': '长度不能超过50'
    }
  };

  /**
   * 创建角色
   */
  onSubmit(){
    this.role = this.roleForm.value;
    this.rolesService.insertRole(this.role).subscribe(
      result =>this.responseUtil.success(result,this.processCreateRoleResult),
      message =>this.responseUtil.error(message)
    );
  }

  /**
   *  获取添加信息
   * @param json
   */
  private processCreateRoleResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success("角色创建成功", () => this.cancelassignRole());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 创建角色之后为账户分配角色
   */
  assignRoleForAccount (role){
    this.accountsService.assignRoles(this.accountId,role.roleId).subscribe(
      result =>this.responseUtil.success(result,this.processAssignRoleResult),
      message =>this.responseUtil.error(message)
    );
  }

  /**
   * 处理角色分配结果
   * @param result
   */
  private processAssignRoleResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success("分配角色成功！", () => this.cancelassignRole());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 角色授权
   * 1.授权之前，保存角色
   */
  authorizationForRole() {
    this.role = this.roleForm.value;
    this.rolesService.insertRole(this.role).subscribe(
      result => this.responseUtil.success(result, this.processSaveRoleResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  角色授权时，处理保存角色结果；
   *  1.授权之前，保存角色之后，调用为账户分配角色；
   * @param result
   */
  private processSaveRoleResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.roleId = result.data.roleId;
        this.assignRoleBeforeAuthority(result.data);

    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 为账户分配角色
   * 1.分配角色；
   * 2.跳转到为角色授权页面；
   * @param role
   */
  private assignRoleBeforeAuthority(role) {
    this.accountsService.assignRoles(this.accountId, role.roleId).subscribe(
      result => this.responseUtil.success(result, this.processAssignRoleBeforeAuthorityResult),
      message => this.responseUtil.error(message)
    );
  }

  /**
   *  处理为账户分配角色结果
   *  1.成功，跳转页面到授权
   * @param result
   */
  private processAssignRoleBeforeAuthorityResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.dialogService.success("角色创建成功，并已分配角色！", () => this.roleAuthority());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   * 角色授权路由
   * @param role
   */
  private roleAuthority() {
    if (!!this.roleId && !!this.menuId) {
      this.router.navigate(['../../roles/authorized', {aRId: this.roleId,mid:this.menuId}], {relativeTo: this.route});
    }
  }


  /**
   * 上一步
   */
  backPreviousStep() {
    this.router.navigate(['../assign',{accoId: this.accountId}], {relativeTo: this.route});
  }

  /**
   * 取消分配角色
   */
  cancelassignRole() {
    this.router.navigate(['..'], {relativeTo: this.route});
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.role = new Role("", "", "", "", "", "", "");
    this.buildForm();
  }

}
